
//
//  SHQiniuManager.m
//  JiFengDaRen
//
//  Created by SH_iOS on 2018/2/8.
//  Copyright © 2018年 SH_iOS. All rights reserved.
//

#import "SHQiniuManager.h"

@implementation SHQiniuManager


#pragma mark - 七牛图片上传


#pragma mark - 上传图片到七牛 默认不压缩
+ (void)qiniuUploadImage:(UIImage *)image
                complete:(void (^)(NSString *qnImageUrl))complete
{

    [self qiniuUploadImage:image scale:NO size:image.size complete:complete];
}

#pragma mark - 上传图片到七牛 压缩图片
+ (void)qiniuUploadImage:(UIImage *)image
                   scale:(BOOL)scale
                    size:(CGSize)size
                complete:(void (^)(NSString *qnImageUrl))complete
{
    
    
    NSData *imageData;
    
    if(scale){
        
        if (UIImagePNGRepresentation(image) == nil) {
            
            imageData = UIImageJPEGRepresentation([SHHelper thumbnailWithImageWithoutScale:image size:size], 1);
            
        } else {
            
            imageData = UIImagePNGRepresentation([SHHelper thumbnailWithImageWithoutScale:image size:size]);
        }
    }else{
        if (UIImagePNGRepresentation(image) == nil) {
            
            imageData = UIImageJPEGRepresentation(image, 1);
            
        } else {
            
            imageData = UIImagePNGRepresentation(image);
        }
        
    }
    
    
    //获取当天日期
    NSString *date = [SHHelper getTodayDate];
    //日期和随机数拼接创建七牛图片存储key
    NSString *qiniuKey = [NSString stringWithFormat:@"%@%d",date,arc4random()/1000];
    NSString *token =  [self tokenWithScope:QiniuBucketName];
    [self  qiniuExtracteWithData:imageData
                        qiniuKey:qiniuKey
                           token:token
                        complete:^(NSString *qnImageUrl) {
    complete(qnImageUrl);

    }];
        
        
   
    
    
}

#pragma mark --  生成token
+ (NSString *)tokenWithScope:(NSString *)scope
{
    QiniuPutPolicy *policy = [QiniuPutPolicy new];
    policy.scope = scope;
    return [policy makeToken:QiniuAccessKey secretKey:QiniuSecretKey];
    
}

#pragma mark - 上传单张图片到七牛
+ (void)qiniuExtracteWithData:(NSData *)data
                     qiniuKey:(NSString *)qiniuKey
                        token:(NSString *)token
                     complete:(void (^)(NSString *qnImageUrl))complete
{
    
    QNUploadManager *uploadManager = [[QNUploadManager alloc] init];
    [uploadManager putData:data key:qiniuKey token:token
                  complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                      if (info.isOK) {
                          SHLog(@"%@", info);
                          SHLog(@"%@", resp);
                          NSString *urlStr = [KQN stringByAppendingString:resp[@"key"]];
                          
                          
                          complete(urlStr);
                      }
                      
                      
                  } option:nil];
}

@end
